// JavaScript Document

var users = {
	
    ajax_page: 'ajax_pages/users.php',
    
    init: function() {

        // initialise the Pane UI JS Library
        if( paneUI ) {
            paneUI.init({
                contentName: 'Users',
                ajax_page: 'ajax_pages/users.php',

                onEditorLoaded: function() {
                    users.bindListeners();
                }
            });    
        }
		
    },
    
    bindListeners: function() {
        var role = document.getElementById("Role");
	
        if( role != null ) {
            users.showSites(role.value, false);
        }
        
        $p(role).bind('change', function() {
            users.showSites(this.value, true);
        });
        
        $p("#submit-btn").bind('click', function() {
            users.saveUserData();
        });
        
        $p("#cancel-btn").bind('click', function() {
            paneUI.hideItemEditor();
        });
    },
	
	bindProfileListeners: function() {
		var role = document.getElementById("Role");
	
        if( role != null ) {
            users.showSites(role.value, false);
        }
        
        $p(role).bind('change', function() {
            users.showSites(this.value, true);
        });
        
        $p("#submit-btn").bind('click', function() {
            users.saveUserData( function() {
				window.location.href = 'index.php';	
			});
        });
        
        $p("#cancel-btn").bind('click', function() {
            window.location.href = 'index.php';
        });
	},
    
    /**
     * 
     */
    saveUserData: function(callback) {
		
		var validated = $p("#user_data_form").validate({
			'FirstName' : 'Please Enter A First Name For This User',
			'LastName' : 'Please Enter A Last Name For This User',
			'Email' : 'Please Provide An Email Address',
			'Username' : 'Please Provide A Username for This User',
			'Password' : 'Please Provide A Password for This User'
		});
		
		if( !validated ) {
			return;	
		}
		
        var query = $p("#userid").val() != "" ? "action=update_user&" : "action=add_user&";
        query = query + $p("#user_data_form").serialize();

        $p.post( users.ajax_page, query, function() {
			if( callback && $p.isFunction(callback) ) {
				callback();
				return;	
			}
			
			paneUI.hideItemEditor();
			
			// reload the current category of articles
            var selected_cat_id = $p("#user_data_form #Role").val();
            var link = paneUI.getCategoryLink(selected_cat_id);
            paneUI.loadItems( link );
        });
    },
	
    showSites: function(type, doDelete) {
        if( type == "specific" || type == 4 ) {
            pageManager.show('sites_div');
        } else {
            pageManager.hide('sites_div');
			
            var sites = document.getElementById("sites");
            if( doDelete && sites.options.length > 0 ) {
                for(var i = 0; i < sites.options.length; i++) {
                    sites.options[i].selected = true;
                }
				
                if( document.getElementById("userid") != null ) {
                    var user = document.getElementById("userid").value;
                    users.deleteSelectedUserSites(user);
                }
            }
        }
    },
	
    deleteSelectedUserSites: function(user) {
        var query = "delsites=1&user=" + user;
        var sites = document.getElementById("sites");
		
        for( var i = 0, j = 1; i < sites.options.length; i++ ) {
            if( sites.options[i].selected ) {
                query = query + "&id" + (j++) + "=" + sites.options[i].value;
            }
        }
		
        pageManager.post('ajax_pages/users.php', query, 'ajax_progress', users.removeSelectedSites );
    },
	
    removeSelectedSites: function() {
        var sites = document.getElementById("sites");
        var cmbSites = document.getElementById("cmbsites");
		
        for( var i = sites.options.length - 1; i >= 0; i-- ) {
            if( sites.options[i].selected ) {
                var newOpt = new Option(sites.options[i].text, sites.options[i].value);
                cmbSites.options.add( newOpt );
                sites.removeChild( sites.options[i] );
            }
        }
    },
	
    addSelectedSite: function() {
        var cmbSites = document.getElementById("cmbsites");
        var sites = document.getElementById("sites");
		
        if( cmbSites != null ) {
            var option = cmbSites.options[ cmbSites.selectedIndex ];
			
            if( option.value == "" ) return;
			
            var siteOption = new Option(option.text, option.value);
            sites.options.add( siteOption );
            cmbSites.removeChild( option );
        }
    },
	
    saveSelectedSite: function(user) {
        var query = "addsites=1&user=" + user;
        var sites = document.getElementById("sites");
		
        for( var i = 0, j = 1; i < sites.options.length; i++ ) {
            query = query + "&id" + (j++) + "=" + sites.options[i].value;
        }
		
        pageManager.post('ajax_pages/users.php', query, 'ajax_progress', users.hideSiteSelector );
    },
	
    showSiteSelector: function() {
        pageManager.show('site_add');
        document.getElementById("sites").disabled = true;
    },
	
    hideSiteSelector: function() {
        pageManager.hide('site_add');
        document.getElementById("sites").disabled = false;
    },
	
    showPassChanger: function() {
        if( document.getElementById("pass-changer").style.display == "none" ){
            pageManager.show('pass-changer');
        } else {
            pageManager.hide('pass-changer', users.clearPassChangeFields );
        }
    },
	
    clearPassChangeFields: function() {
        document.getElementById("OldPassword").value = "";
        document.getElementById("NewPassword").value = "";
        document.getElementById("ConfirmPassword").value = "";
        document.getElementById("pass-process").innerHTML = "";
    },
	
    changePassword: function() {
        // ensure the new password is properly confirmed
        var newPass = document.getElementById("NewPassword").value;
        var confirmation = document.getElementById("ConfirmPassword").value;
        var oldPass = document.getElementById("OldPassword").value;
        var user = document.getElementById("userid").value;
		
        if( newPass != confirmation ) {
            alert("The New Password and its confirmation do not match. Please correct!");
            return;
        }
		
        var query = "changepass=1&user=" + user + "&old=" + oldPass + "&new=" + newPass;
        //alert(query);
        pageManager.post('ajax_pages/users.php', query, 'pass-process', users.postProcessPassChange );
    },
	
    postProcessPassChange: function() {
        var content = document.getElementById("pass-process").innerHTML;
		
        if( content.indexOf("Password Change Successful") == -1 ) {
            alert("The password could not be changed due to the following error:\n\n" + content);
            document.getElementById("pass-process").innerHTML = "";
            return;
        } else {
            alert(content);
            // since the pass changer is visible, it will be hidden, and the field contents cleared
            users.showPassChanger();
        }
    }
};

pageManager.addLoadEvent( function() {
    users.init();
	
    var level = document.getElementById("Level");
	
    if( level != null ) {
        users.showSites(level.value, false);
    }
});